﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZDSoft.UPMS.Service.BusinessPart;
using ZDSoft.UPMS.Model.BusinessPart;
using ZDSoft.UPMS.Core;
using System.Data.SqlClient;
using System.IO;
using System.Text;

namespace ZDSoft.UPMS.Web.Controllers
{
    public class RuleController : Controller
    {
        string typeOption = "";
        SituationType model = new SituationType();
        SituationType allType = new SituationType();

        public ActionResult CreateRlueIndex(string name)
        {
            allType = Container.Instance.Resolve<ISituationTypeService>().FindAll().Where(o => o.Name == name).FirstOrDefault();
            if (name != null)
            {
                typeOption = "<option  value='" + allType.ID + "," + allType.Name + "'>" + allType.Name + " </option>";
            }
            show();
            IList<SituationType> entity = new List<SituationType>();
            SituationType CC = new SituationType();
            if (allType == null)
            {
                if (model.Children != null)
                {
                    foreach (SituationType entityone in model.Children)
                    {
                        entity.Add(entityone);
                    }
                }
                else
                {
                    entity.Add(model);
                }
            }
            else if (allType.Children.Count() == 0)
            {
                entity.Add(allType);
            }
            else
            {
                foreach (SituationType one in allType.Children)
                {
                    entity.Add(one);
                }
            }
            return View(entity);
        }

        public void show()
        {
            IList<SituationType> allType = Container.Instance.Resolve<ISituationTypeService>().FindAll();
            IList<SituationType> list = new List<SituationType>();
            IList<string> strList = new List<string>();
            int i = 0;
            foreach (SituationType type in allType)
            {

                if (type.Parent == null)
                {
                    model = allType[0];
                    typeOption += "<option  value='" + type.ID + "," + type.Name + "'>" + type.Name + " </option>";
                    i++;
                }

            }
            string sele = "<select id='SituationType'>" + typeOption + "</select>";

            TempData["types"] = sele;
        }


        /// <summary>
        /// 动态在数据库中创建函数
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="up"></param>
        /// <param name="down"></param>
        /// <param name="str"></param>
        public void CreateFunction(string pid, int up, int down, string str)
        {
            //创建函数名称
            string Name = "GetScor" + pid;
            //实例化一个创建函数的字符串
            string rule = "";
            //判断函数是否已经存在
            bool IsHave = Container.Instance.Resolve<ISituationTypeService>().IsHaveFunction(Name);
            //如果存在先删除原函数
            if (IsHave)
            {
                rule += "exec sp_executesql N'";
                rule += "drop FUNCTION dbo.GetScor" + pid + "'";
            }
            //动态拼凑创建函数的字符串
            int i = 0;
            string[] strtrs = str.Split('|');
            SituationType ParentType = Container.Instance.Resolve<ISituationTypeService>().FindByID(int.Parse(pid));
            int k = ParentType.Children.Count();
            IList<SituationType> SituationTypes = ParentType.Children;
            rule += "exec sp_executesql N' CREATE FUNCTION dbo.GetScor" + pid + "(@ParentSituationType int,@ChildSituationType int,@Times int,@lesson int)  RETURNS numeric(18,1) AS  BEGIN Declare @dblReturn numeric(18,1) ";
            rule += " IF (@ParentSituationType =" + ParentType.ID + ") BEGIN ";
            rule += " IF (" + up + "<=@lesson AND @lesson <=" + down + ") BEGIN ";
            foreach (SituationType situationType in SituationTypes)
            {
                if (i < strtrs.Length)
                {
                    if (strtrs[i].Length == 1)
                    {
                        rule += "IF (@ChildSituationType = " + situationType.ID + ") BEGIN set @dblReturn=@Times*" + strtrs[i] + " END ";
                    }
                    if (strtrs[i].Length > 1)
                    {
                        rule += "IF (@ChildSituationType = " + situationType.ID + ") BEGIN ";
                        string[] strtds = strtrs[i].Split('-');
                        for (int j = 0; j < strtds.Length; j++)
                        {
                            string[] strTimesAndScor = strtds[j].Split('!');
                            string[] strTimes = strTimesAndScor[0].Split(',');
                            rule += " IF (" + strTimes[0] + "<=@Times AND @Times <=" + strTimes[1] + " ) BEGIN	set @dblReturn = @times * " + strTimesAndScor[1] + " END ";
                        }
                        rule += " END ";
                    }
                    i++;
                }
            }
            rule += " END END return @dblReturn END' ";
            //执行创建函数方法
            Container.Instance.Resolve<IRuleService>().Exec(rule);

            string Path = Server.MapPath("../Content/tab/Code.txt");
            List<string[]> list = new List<string[]>();
            list = ReadInfoFromFile(Path);
            string[] str1 = new string[4];
            str1[0] = pid;
            str1[1] = up.ToString();
            str1[2] = down.ToString();
            str1[3] = str;
            list.Add(str1);
            WriteInfoTofile(Path, list);
        }


        public ActionResult Delete(int ID)
        {
            string str = "";
            str += "exec sp_executesql N'";
            str += "drop FUNCTION dbo.GetScor" + ID + "'";

            string Path = Server.MapPath("../../Content/tab/Code.txt");
            List<string[]> newlist = new List<string[]>();
            List<string[]> list = new List<string[]>();
            list = ReadInfoFromFile(Path);
            foreach (string[] strs in list)
            {
                if (strs[0] != ID.ToString())
                {
                    newlist.Add(strs);
                }
            }
            WriteInfoTofile(Path, newlist);
            Container.Instance.Resolve<IRuleService>().Exec(str);
            return RedirectToAction("SituationRuleList");
        }

        /// <summary>
        /// 这个函数把文件的每一行读入list
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        private static List<string[]> ReadInfoFromFile(string Path)
        {
            if (System.IO.File.Exists(Path))
            {
                List<string[]> list = new List<string[]>();
                using (StreamReader sr = new StreamReader(Path, Encoding.GetEncoding("GBK")))
                {
                    while (!sr.EndOfStream)
                    {
                        string temp = sr.ReadLine();
                        string[] strArray = temp.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);//将拆分好string[]存入list
                        list.Add(strArray);
                    }
                }
                return list;
            }
            return null;
        }

        /// <summary>
        /// 把list中的每一行写入文件
        /// </summary>
        /// <param name="Path"></param>
        /// <param name="list"></param>
        private static void WriteInfoTofile(string Path, List<string[]> list)
        {
            using (StreamWriter sw = new StreamWriter(Path, false, Encoding.GetEncoding("GBK")))
            {
                foreach (string[] strArray in list)
                {
                    string line = string.Empty;
                    foreach (string temp in strArray)
                    {
                        if (!string.IsNullOrEmpty(temp))
                        {
                            line += temp;
                            line += "\t";
                        }
                    }
                    sw.WriteLine(line);
                }
            }
        }

        public ActionResult SituationRuleList()
        {
            int i;
            List<string[]> SituationRuleList = new List<string[]>();
            string Path = Server.MapPath("../Content/tab/Code.txt");
            List<string[]> list = new List<string[]>();
            list = ReadInfoFromFile(Path);
            foreach (string[] strs in list)
            {
                i = 0;
                SituationType situation = Container.Instance.Resolve<ISituationTypeService>().FindByID(Convert.ToInt32(strs[0]));
                string[] strRule = strs[3].Split('|');
                string[] str = new string[5];
                str[0] = situation.Name;
                str[4] = situation.ID.ToString();
                foreach (SituationType situationrule in situation.Children)
                {


                    str[1] += situationrule.Name + ",";
                    if (strRule[i].Length == 1)
                    {
                        str[2] += "实际情况" + ",";
                        str[3] += "每次扣" + strRule[i] + "分" + ",";
                    }
                    else
                    {
                        str[2] += "阶段性" + ",";
                        string[] rules = strRule[i].Split('-');
                        foreach (string rule in rules)
                        {
                            string[] scores = rule.Split(',');
                            str[3] += scores[0] + "--" + scores[1].Replace("!", "每次扣") + "分    ";
                        }
                        str[3] += ",";
                    }
                    i++;
                }
                for (int k = 1; k < 4; k++)
                {
                    str[k] = str[k].Substring(0, str[k].Length - 1);
                }
                SituationRuleList.Add(str);
            }
            TempData["SituationRuleList"] = SituationRuleList;
            return View();
        }



    }
}
